<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-row>
        <el-col>
          <el-form-item label="交易方信息" prop="poolCounterparty">
            <el-input
              v-model="queryParams.poolCounterparty"
              placeholder="请输入交易方信息"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="入账金额" prop="poolInAmount">
            <el-input
              v-model="queryParams.poolInAmount"
              placeholder="请输入入账金额"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="出账金额" prop="poolOutAmount">
            <el-input
              v-model="queryParams.poolOutAmount"
              placeholder="请输入出账金额"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item label="资金余额" prop="poolBalance">
            <el-select
              v-model="queryParams.poolBalance"
              placeholder="请选择资金余额"
            >
              <el-option label="全部" value="" />
              <el-option label="0" value="0" />
              <el-option label="非0" value="non-zero" />
            </el-select>
          </el-form-item>
          <el-form-item label="出账时间">
            <el-date-picker
              v-model="queryParams.poolOutTimeRange"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
              clearable
              style="width: 215px"
            />
          </el-form-item>
          <el-form-item label="入账时间">
            <el-date-picker
              v-model="queryParams.poolTransactionDateRange"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
              clearable
              style="width: 215px"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <!-- 左侧操作按钮 -->
      <el-col :span="1.5">
        <el-button type="primary" plain @click="handleExport">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain @click="handleDeposit">入账</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain @click="handleEditDeposit()"
          >编辑入账</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain @click="handleWithdrawal()"
          >出账</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain @click="handleEditWithdrawal"
          >编辑出账</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          :disabled="multiple"
          @click="handleRemoveFundPool()"
          >删除</el-button
        >
      </el-col>

      <!-- 右侧浮动按钮组 -->
      <el-col :span="6" style="float: right; margin-top: 0">
        <el-button-group>
          <el-button type="primary" plain @click="toggleSearch"
            >隐藏搜索</el-button
          >
          <el-button type="primary" plain @click="refreshTable">刷新</el-button>
          <el-button type="primary" plain @click="toggleSort"
            >隐藏/排序列</el-button
          >
        </el-button-group>
      </el-col>
    </el-row>

    <!-- 按钮组件 -->
    <deposit-dialog
      :visible.sync="depositDialogVisible"
      :title="depositTitle"
      :formData="depositFormData"
      @submit="handleDepositSubmit"
    />
    <withdrawal-dialog
      ref="withdrawalDialog"
      :visible.sync="withdrawalDialogVisible"
      :title="withdrawalTitle"
      :formData="withdrawalFormData"
      @submit="handleWithdrawalSubmit"
      @open-relation-dialog="handleOpenRelationDialog"
    />
    <WithdrawalRelationDialog
      :visible.sync="relationDialogVisible"
      @confirm="handleRelationConfirm"
    />

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="poolList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="交易号"
        align="center"
        prop="poolTransactionNum"
      />
      <el-table-column
        label="交易时间"
        align="center"
        prop="poolTransactionDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.poolTransactionDate, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="交易方信息"
        align="center"
        prop="poolCounterparty"
      />
      <el-table-column label="交易方账号" align="center" prop="poolAccount" />
      <el-table-column label="交易银行" align="center" prop="poolBank" />
      <el-table-column label="入账金额" align="center" prop="poolInAmount" />
      <el-table-column label="转账备注" align="center" prop="poolRemark" />
      <el-table-column
        label="出账信息"
        align="center"
        prop="poolOutInformation"
      />
      <el-table-column label="出账金额" align="center" prop="poolOutAmount" />
      <el-table-column
        label="出账时间"
        align="center"
        prop="poolOutTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.poolOutTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="资金余额" align="center" prop="poolBalance" />
      <el-table-column
        label="操作"
        align="center"
        width="160px"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button type="text" @click="handleEditDeposit(scope.row)"
            >修改入账</el-button
          >
          <el-button type="text" @click="handleWithdrawal(scope.row)"
            >出账</el-button
          >
          <el-button type="text" @click="handleRemoveFundPool(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改资金池对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="报名id" prop="registrationId">
          <el-input v-model="form.registrationId" placeholder="请输入报名id" />
        </el-form-item>
        <el-form-item label="交易号" prop="poolTransactionNum">
          <el-input
            v-model="form.poolTransactionNum"
            placeholder="请输入交易号"
          />
        </el-form-item>
        <el-form-item label="交易时间" prop="poolTransactionDate">
          <el-date-picker
            clearable
            v-model="form.poolTransactionDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择交易时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="交易方" prop="poolCounterparty">
          <el-input
            v-model="form.poolCounterparty"
            placeholder="请输入交易方"
          />
        </el-form-item>
        <el-form-item label="交易账号" prop="poolAccount">
          <el-input v-model="form.poolAccount" placeholder="请输入交易账号" />
        </el-form-item>
        <el-form-item label="交易银行" prop="poolBank">
          <el-input v-model="form.poolBank" placeholder="请输入交易银行" />
        </el-form-item>
        <el-form-item label="入账金额" prop="poolInAmount">
          <el-input v-model="form.poolInAmount" placeholder="请输入入账金额" />
        </el-form-item>
        <el-form-item label="出账信息" prop="poolOutInformation">
          <el-input
            v-model="form.poolOutInformation"
            placeholder="请输入出账信息"
          />
        </el-form-item>
        <el-form-item label="出账金额" prop="poolOutAmount">
          <el-input v-model="form.poolOutAmount" placeholder="请输入出账金额" />
        </el-form-item>
        <el-form-item label="出账时间" prop="poolOutTime">
          <el-date-picker
            clearable
            v-model="form.poolOutTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择出账时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="转账备注" prop="poolRemark">
          <el-input v-model="form.poolRemark" placeholder="请输入转账备注" />
        </el-form-item>
        <el-form-item label="资金余额" prop="poolBalance">
          <el-input v-model="form.poolBalance" placeholder="请输入资金余额" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import WithdrawalRelationDialog from "@/components/Pool/WithdrawalRelationDialog.vue";
import {
  listPool,
  getPool,
  delPool,
  addPool,
  updatePool,
  disbursement,
  removeFundPool,
  getFundPoolCorrelationInfo,
} from "@/api/payment/pool";
//入账按钮
import DepositDialog from "@/components/Pool/DepositDialog.vue";
//出账按钮
import WithdrawalDialog from "@/components/Pool/WithdrawalDialog.vue";

export default {
  name: "Pool",
  components: { DepositDialog, WithdrawalDialog, WithdrawalRelationDialog },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 资金池表格数据
      poolList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        poolTransactionDate: null,
        poolCounterparty: null,
        poolAccount: null,
        poolBank: null,
        poolOutInformation: null,
        poolOutTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},

      //新增定义
      //入账按钮
      depositDialogVisible: false,
      depositTitle: "入账",
      depositFormData: {
        // poolTransactionNum: "",
        // poolTransactionDate: null,
        // poolCounterparty: "",
        // poolAccount: "",
        // poolBank: "",
        // poolInAmount: null,
        // poolRemark: "",
      },
      // 出账相关数据
      withdrawalDialogVisible: false,
      withdrawalTitle: "出账",
      withdrawalFormData: {
        poolTransactionNum: "",
        poolOutTime: null,
        poolCounterparty: "",
        poolAccount: "",
        poolBank: "",
        poolOutAmount: null,
        poolRemark: "",
      },
      //
      relationDialogVisible: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询资金池列表 */
    getList() {
      this.loading = true;
      listPool(this.queryParams).then((response) => {
        this.poolList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        fundPoolId: null,
        registrationId: null,
        poolTransactionNum: null,
        poolTransactionDate: null,
        poolCounterparty: null,
        poolAccount: null,
        poolBank: null,
        poolInAmount: null,
        poolOutInformation: null,
        poolOutAmount: null,
        poolOutTime: null,
        poolRemark: null,
        poolBalance: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        exampleOne: null,
        exampleTwo: null,
        exampleThree: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.poolOutTimeRange = null;
      this.queryParams.poolTransactionDateRange = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.fundPoolId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加资金池";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const fundPoolId = row.fundPoolId || this.ids;
      getPool(fundPoolId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改资金池";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.fundPoolId != null) {
            updatePool(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPool(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const fundPoolIds = row.fundPoolId || this.ids;
      this.$modal
        .confirm('是否确认删除资金池编号为"' + fundPoolIds + '"的数据项？')
        .then(function () {
          return delPool(fundPoolIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "training/pool/export",
        {
          ...this.queryParams,
        },
        `pool_${new Date().getTime()}.xlsx`
      );
    },

    //新增方法
    //逻辑删除
    handleRemoveFundPool(row) {
      // const fundPoolIds = row.fundPoolId || this.ids;

      let fundPoolIds;

      if (row) {
        // 单行删除 - 从行数据获取ID
        fundPoolIds = row.fundPoolId;
      } else {
        // 批量删除 - 从选中项获取ID
        fundPoolIds = this.ids;
      }

      this.$modal
        .confirm('是否确认删除资金池编号为"' + fundPoolIds + '"的数据项？')
        .then(function () {
          return removeFundPool(fundPoolIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    //刷新按钮组
    toggleSearch() {
      this.showSearch = !this.showSearch;
    },
    refreshTable() {
      this.getList();
    },
    toggleSort() {
      // 实现排序列切换逻辑
    },

    //入账按钮
    // 打开入账对话框
    handleDeposit() {
      console.log("Opening deposit dialog");
      this.depositTitle = "入账";
      this.depositFormData = {
        poolTransactionNum: "",
        poolTransactionDate: null,
        poolCounterparty: "",
        poolAccount: "",
        poolBank: "",
        poolInAmount: null,
        poolRemark: "",
      };
      this.depositDialogVisible = true;
      console.log("Deposit dialog visible:", this.depositDialogVisible);
    },
    // 提交入账数据
    handleDepositSubmit(formData) {
      const fundPoolId = this.ids[0];
      // 判断是新增还是编辑
      if (formData.fundPoolId != null) {
        // 如果formData中已经有fundPoolId，说明是编辑操作
        updatePool(formData).then((response) => {
          this.$modal.msgSuccess("编辑入账成功");
          this.getList(); // 刷新列表
        });
      } else if (fundPoolId != null) {
        // 如果有选中记录ID，也是编辑操作
        formData.fundPoolId = fundPoolId;
        updatePool(formData).then((response) => {
          this.$modal.msgSuccess("编辑入账成功");
          this.getList(); // 刷新列表
        });
      } else {
        // 否则为新增操作
        addPool(formData).then((response) => {
          this.$modal.msgSuccess("入账成功");
          this.getList(); // 刷新列表
        });
      }
    },
    // 编辑入账
    handleEditDeposit(row) {
      // 如果没有传入row且未选择记录，则提示选择
      if (!row && this.ids.length !== 1) {
        this.$modal.msgWarning("请先选择一条记录");
        return;
      }

      // 使用传入的行数据或选中的第一条数据
      const targetRow =
        row || this.poolList.find((item) => item.fundPoolId === this.ids[0]);

      if (targetRow) {
        getPool(targetRow.fundPoolId)
          .then((response) => {
            // 添加对响应数据的检查
            if (response && response.data) {
              const data = response.data;
              this.depositFormData = {
                fundPoolId: targetRow.fundPoolId,
                poolTransactionNum: data.poolTransactionNum || "",
                poolTransactionDate: data.poolTransactionDate || null,
                poolCounterparty: data.poolCounterparty || "",
                poolAccount: data.poolAccount || "",
                poolBank: data.poolBank || "",
                poolInAmount: data.poolInAmount || null,
                poolRemark: data.poolRemark || "",
              };
              this.depositTitle = "编辑入账";
              this.depositDialogVisible = true;
            } else {
              this.$modal.msgError("获取数据失败");
            }
          })
          .catch((error) => {
            console.error("获取资金池详情失败:", error);
            this.$modal.msgError("获取数据失败");
          });
      }
    },
    // 出账按钮
    handleWithdrawal(row) {
      // 如果没有传入row且未选择记录，则提示选择
      if (!row && this.ids.length !== 1) {
        this.$modal.msgWarning("请先选择一条记录");
        return;
      }

      // 使用传入的行数据或选中的第一条数据
      const targetRow =
        row || this.poolList.find((item) => item.fundPoolId === this.ids[0]);

      if (targetRow) {
        // 实现出账逻辑
        this.withdrawalTitle = "出账";
        this.withdrawalFormData = {
          fundPoolId: targetRow.fundPoolId,
          poolTransactionNum: "",
          poolOutTime: null,
          poolCounterparty: "",
          poolAccount: "",
          poolBank: "",
          poolOutAmount: null,
          poolRemark: "",
        };
        this.withdrawalDialogVisible = true;

        // 添加人员信息回显功能
        getFundPoolCorrelationInfo(targetRow.fundPoolId)
          .then((response) => {
            if (response && response.data) {
              const data = response.data;

              // 回显已有关联的报名人员信息
              if (
                data.registrationDtoList &&
                Array.isArray(data.registrationDtoList)
              ) {
                this.$nextTick(() => {
                  if (this.$refs.withdrawalDialog) {
                    // 直接设置 WithdrawalDialog 组件的 selectedRegistrations 数据
                    this.$refs.withdrawalDialog.selectedRegistrations =
                      data.registrationDtoList.map((item) => ({
                        id: item.registrationId,
                        registrationId: item.registrationId,
                        studentName: item.studentName || "",
                        idNumber: item.idNumber || "",
                        projectSum: item.projectSum || "",
                      }));
                  }
                });
              }
            }
          })
          .catch((error) => {
            console.error("获取资金池关联信息失败:", error);
          });
      }
    },
    // 编辑出账
    handleEditWithdrawal() {
      if (this.ids.length !== 1) {
        this.$modal.msgWarning("请先选择一条记录");
        return;
      }

      const fundPoolId = this.ids[0];

      getFundPoolCorrelationInfo(fundPoolId)
        .then((response) => {
          console.log("response.data:", response.data);
          if (response && response.data) {
            const data = response.data;

            // 设置表单基础数据（注意这里要从完整的data对象中获取）
            this.withdrawalFormData = {
              fundPoolId: fundPoolId,
              poolTransactionNum: data.poolTransactionNum || "",
              poolOutTime: data.poolOutTime || null,
              poolCounterparty: data.poolCounterparty || "",
              poolAccount: data.poolAccount || "",
              poolBank: data.poolBank || "",
              poolOutAmount: data.poolOutAmount || null,
              poolRemark: data.poolRemark || "",
            };

            // 回显已有关联的报名人员信息
            if (
              data.registrationDtoList &&
              Array.isArray(data.registrationDtoList)
            ) {
              // 先打开对话框
              this.withdrawalTitle = "编辑出账";
              this.withdrawalDialogVisible = true;

              // 在下一个事件循环中设置已选的报名信息
              this.$nextTick(() => {
                if (this.$refs.withdrawalDialog) {
                  // 直接设置 WithdrawalDialog 组件的 selectedRegistrations 数据
                  this.$refs.withdrawalDialog.selectedRegistrations =
                    data.registrationDtoList.map((item) => ({
                      id: item.registrationId,
                      registrationId: item.registrationId,
                      studentName: item.studentName || "",
                      idNumber: item.idNumber || "",
                      projectSum: item.projectSum || "",
                    }));
                }
              });
            } else {
              // 如果没有关联的报名信息，直接打开对话框
              this.withdrawalTitle = "编辑出账";
              this.withdrawalDialogVisible = true;
            }
          } else {
            this.$modal.msgError("获取数据失败");
          }
        })
        .catch((error) => {
          console.error("获取资金池详情失败:", error);
          this.$modal.msgError("获取数据失败");
        });
    },
    // 提交出账数据
    handleWithdrawalSubmit(formData) {
      // 存在 registrations 数组且不为空，则处理 registrationId
      if (formData.registrations && formData.registrations.length > 0) {
        // 提取所有 registrationId 并拼接成字符串，用逗号分隔
        const registrationIds = formData.registrations
          .map((reg) => reg.registrationId)
          .join(",");

        // 将拼接后的字符串添加到提交数据中
        formData.registrationId = registrationIds;
      }
      const fundPoolId = formData.fundPoolId || this.ids[0];
      if (!fundPoolId) {
        this.$modal.msgWarning("未选择有效的记录");
        return;
      }
      formData.fundPoolId = fundPoolId;

      var params = {
        fundPoolId: fundPoolId,
        registrationId: formData.registrationId,
      };

      disbursement(params).then((response) => {
        this.$modal.msgSuccess("出账成功");
        this.getList(); // 刷新列表
      });
    },
    // 添加打开关联对话框的方法
    handleOpenRelationDialog() {
      this.relationDialogVisible = true;
    },
    // 添加处理关联确认的方法
    handleRelationConfirm(selectedItems) {
      // 确保引用正确且组件已渲染
      if (
        this.$refs.withdrawalDialog &&
        typeof this.$refs.withdrawalDialog.handleRelationConfirm === "function"
      ) {
        // 将选中的报名信息传递给 WithdrawalDialog
        this.$refs.withdrawalDialog.handleRelationConfirm(selectedItems);
      } else {
        console.error(
          "WithdrawalDialog component or handleRelationConfirm method not found"
        );
      }
      this.relationDialogVisible = false;
    },
  },
};
</script>
<style scoped>
.el-button-group {
  background-color: transparent !important;
}
</style>